<template>
  <div class="contacts-container">
    <el-card class="page-container">
      <!-- 页面头部 -->
      <template #header>
        <div class="page-header">
          <div class="header-left">
            <el-button 
              @click="handleBack"
              :icon="ArrowLeft"
              circle
            />
            <h2 class="page-title" v-if="type == 1">
              <el-icon><User /></el-icon>
              {{ groupName }} - 微信号联系人列表
            </h2>
            <h2 class="page-title" v-if="type == 2">
              <el-icon><User /></el-icon>
              {{ groupName }} - 手机号联系人列表
            </h2>
          </div>
          <el-button 
            type="primary" 
            @click="handleAdd"
            :icon="Plus"
          >
            新增联系人
          </el-button>
        </div>
      </template>

      <!-- 状态统计图表 -->
      
      <div class="stats-section">
        <el-card class="stats-card" shadow="hover">
          <template #header>
            <div class="stats-header">
              <span class="stats-title">联系人状态分布</span>
              <el-button 
                type="primary" 
                size="small"
                @click="fetchContactStats"
                :loading="statsLoading"
              >
                <el-icon><Refresh /></el-icon>
                刷新统计
              </el-button>
            </div>
          </template>
          <div class="stats-content">
            <div ref="chartRef" class="chart-container" v-loading="statsLoading"></div>
            <div class="stats-summary">
              <div class="summary-item">
                <span class="summary-label">总计：</span>
                <span class="summary-value">{{ totalContacts }}人</span>
              </div>
              <div class="summary-grid">
                <div 
                  v-for="item in statsData" 
                  :key="item.status" 
                  class="summary-stat"
                >
                  <div class="stat-dot" :style="{ backgroundColor: item.color }"></div>
                  <span class="stat-label">{{ item.name }}：</span>
                  <span class="stat-value">{{ item.value }}人</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      

      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form 
          :model="searchForm" 
          inline
          class="search-form"
        >
          <el-form-item label="联系人信息 ">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入联系人信息"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="待投放" value="0" />
              <el-option label="投放中" value="1" />
              <el-option label="已投放" value="2" />
              <el-option label="投放失败" value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              @click="handleSearch"
              :loading="loading"
            >
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table-section">
        <el-table
          :data="tableData"
          v-loading="loading"
          style="width: 100%"
          border
          stripe
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="contact_info" label="联系人信息" min-width="200" />
          <el-table-column prop="tag" label="标签" min-width="200">
            <template #default="{ row }">
              <el-tag 
                v-for="tag in row.tag" 
                :key="tag" 
                size="small"
                style="margin-right: 5px"
              >
                {{ tag }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="import_batch_id" label="导入批次ID" width="120" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag 
                :type="getStatusType(row.status)"
                size="small"
              >
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="120" />
          <el-table-column prop="created_at" label="导入时间" width="180" />
          <el-table-column prop="fail_reason" label="失败原因"  width="250">
            <template #default="{ row }">
              <span v-if="row.fail_reason" class="fail-reason">
                {{ row.fail_reason }}
              </span>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="updated_at" label="投放时间" width="180" />
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              
              <el-button 
                type="danger" 
                size="small"
                @click="handleDelete(row)"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增联系人弹框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增联系人"
      width="600px"
      @close="handleAddDialogClose"
    >
      <!-- 导入方式选择 -->
      <div class="import-type-section">
        <el-radio-group v-model="importType">
          <el-radio value="manual">手动批量添加</el-radio>
          <el-radio value="excel">Excel导入</el-radio>
        </el-radio-group>
      </div>

      <!-- 手动添加 -->
      <div v-if="importType === 'manual'" class="manual-section">
        <!-- 标签设置区域 -->
        <div class="tags-section">
          <div class="tags-header">
            <h4>设置标签（可选）</h4>
          </div>
          <div class="tags-content">
            <el-tag
              v-for="(tag, index) in manualTags"
              :key="index"
              closable
              @close="removeManualTag(index)"
              style="margin-right: 8px; margin-bottom: 4px;"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="manualTagInputVisible"
              ref="manualTagInputRef"
              v-model="manualTagInputValue"
              size="small"
              style="width: 120px; margin-right: 8px;"
              @keyup.enter="addManualTag"
              @blur="addManualTag"
              placeholder="输入标签"
            />
            <el-button
              v-else
              size="small"
              @click="showManualTagInput"
            >
              + 添加标签
            </el-button>
            <div class="tags-tip">
              <span>为本次添加的联系人统一添加标签，便于后续管理</span>
            </div>
          </div>
        </div>

        <!-- 联系人信息输入 -->
        <el-form
          ref="addFormRef"
          :model="addForm"
          :rules="addFormRules"
          label-width="100px"
        >
        
          <el-form-item label="联系人信息" prop="contacts" v-if="type == 1">
            <el-input
              v-model="addForm.contacts"
              type="textarea"
              :rows="8"
              placeholder="请输入微信号，每行一个微信号，格式：&#10;forever794889&#10;dd123456"
              maxlength="5000"
              show-word-limit
            />
          </el-form-item>


          <el-form-item label="联系人信息" prop="contacts" v-if="type == 2">
            <el-input
              v-model="addForm.contacts"
              type="textarea"
              :rows="8"
              placeholder="请输入手机号，每行一个手机号，格式：&#10;13312345678&#10;17712345678"
              maxlength="5000"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- Excel导入 -->
      <div v-if="importType === 'excel'" class="excel-section">
        <!-- 安全提示 -->
        <div class="security-notice">
          <el-icon class="security-icon"><Lock /></el-icon>
          <span class="security-text">您的数据将被加密处理，请放心上传</span>
        </div>

        <!-- 模板下载区域 -->
        <div class="template-section">
          <div class="template-header">
            <h4>第一步：下载模板</h4>
          </div>
          <div class="template-content">
            <el-button 
              type="primary" 
              @click="downloadTemplate"
              :icon="Download"
            >
              下载Excel模板
            </el-button>
            <div class="template-tips">
              <p>• 请按照模板格式填写联系人信息</p>
              <p v-if="type == 1">• 支持格式：微信号</p>
              <p v-if="type == 2">• 支持格式：手机号</p>
              <p>• 建议单次上传不超过1000条数据</p>
            </div>
          </div>
        </div>

        <!-- 标签设置区域 -->
        <div class="tags-section">
          <div class="tags-header">
            <h4>第二步：设置标签（可选）</h4>
          </div>
          <div class="tags-content">
            <el-tag
              v-for="(tag, index) in importTags"
              :key="index"
              closable
              @close="removeImportTag(index)"
              style="margin-right: 8px; margin-bottom: 4px;"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="importTagInputVisible"
              ref="importTagInputRef"
              v-model="importTagInputValue"
              size="small"
              style="width: 120px; margin-right: 8px;"
              @keyup.enter="addImportTag"
              @blur="addImportTag"
              placeholder="输入标签"
            />
            <el-button
              v-else
              size="small"
              @click="showImportTagInput"
            >
              + 添加标签
            </el-button>
            <div class="tags-tip">
              <span>为本次导入的联系人统一添加标签，便于后续管理</span>
            </div>
          </div>
        </div>

        <!-- 文件上传区域 -->
        <div class="upload-section">
          <div class="upload-header">
            <h4>第三步：上传文件</h4>
          </div>
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :show-file-list="true"
            :limit="1"
            accept=".xlsx,.xls"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            drag
            class="upload-area"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将Excel文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                <div class="upload-tips">
                  <p>• 只能上传xlsx/xls文件，且不超过10MB</p>
                  <p>• 请确保文件格式与模板一致</p>
                  <p>• 上传前请检查数据的完整性和准确性</p>
                </div>
              </div>
            </template>
          </el-upload>
        </div>

        <!-- 上传进度 -->
        <div v-if="uploadProgress > 0" class="progress-section">
          <el-progress 
            :percentage="uploadProgress" 
            :status="uploadStatus"
          />
          <p class="progress-text">{{ uploadProgressText }}</p>
        </div>
      </div>

      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleAddSubmit"
          :loading="addSubmitLoading"
        >
          确定添加
        </el-button>
      </template>
    </el-dialog>

    <!-- 编辑联系人弹框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑联系人"
      width="500px"
      @close="handleEditDialogClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item label="联系人信息" prop="contactInfo">
          <el-input
            v-model="editForm.contactInfo"
            placeholder="请输入联系人信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleEditSubmit"
          :loading="editSubmitLoading"
        >
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox, type FormInstance, type UploadInstance } from 'element-plus'
import { 
  User, Plus, Search, Refresh, Edit, Delete, ArrowLeft, UploadFilled, Download, Lock
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  getContactList,
  addContact,
  updateContact,
  deleteContact,
  importContactsFromExcel,
  getContactStats,
  type Contact
} from '@/api/customer-group'

const router = useRouter()
const route = useRoute()

// 从路由参数获取客群库信息
const groupId = ref<number>(Number(route.query.groupId))
const groupName = ref<string>(String(route.query.groupName || ''))
const type = ref<string>(String(route.query.type || ''))

// 响应式数据
const loading = ref(false)
const addSubmitLoading = ref(false)
const editSubmitLoading = ref(false)
const statsLoading = ref(false)
const tableData = ref<Contact[]>([])
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const importType = ref<'manual' | 'excel'>('manual')
const activeNames = ref(['0']);
const type_words = ref('')

// 统计相关
const chartRef = ref<HTMLElement>()
const statsData = ref<Array<{
  status: string
  name: string
  value: number
  color: string
}>>([])
const totalContacts = ref(0)

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0
})

// 新增表单
const addFormRef = ref<FormInstance>()
const addForm = reactive({
  contacts: ''
})

const addFormRules = {
  contacts: [
    { required: true, message: '请输入联系人信息', trigger: 'blur' },
    { min: 1, message: '请至少输入一个联系人信息', trigger: 'blur' }
  ]
}

// 编辑表单
const editFormRef = ref<FormInstance>()
const editForm = reactive({
  contactInfo: ''
})
const currentEditId = ref<number | null>(null)

const editFormRules = {
  contactInfo: [
    { required: true, message: '请输入联系人信息', trigger: 'blur' },
    { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
  ]
}

// 文件上传
const uploadRef = ref<UploadInstance>()
const selectedFile = ref<File | null>(null)

// 导入标签相关
const importTags = ref<string[]>([])
const importTagInputVisible = ref(false)
const importTagInputValue = ref('')
const importTagInputRef = ref<HTMLInputElement>()

// 上传进度相关
const uploadProgress = ref(0)
const uploadStatus = ref<'success' | 'exception' | 'warning' | ''>('')
const uploadProgressText = ref('')

// 手动标签相关
const manualTags = ref<string[]>([])
const manualTagInputVisible = ref(false)
const manualTagInputValue = ref('')
const manualTagInputRef = ref<HTMLInputElement>()

// 状态处理
const getStatusType = (status: string): 'success' | 'warning' | 'info' | 'primary' | 'danger' => {
  const statusMap: Record<string, 'success' | 'warning' | 'info' | 'primary' | 'danger'> = {
    0: 'info',     // 待投放 - 灰色
    1: 'primary',  // 投放中 - 蓝色  
    2: 'success',  // 已投放 - 绿色
    3: 'danger'    // 投放失败 - 红色
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    0: '待投放',
    1: '投放中',
    2: '已投放',
    3:'投放失败'
  }
  return statusMap[status] || '未知'
}

// 获取列表数据
const getList = async () => {
  try {
    loading.value = true
    const params = {
      library_id: groupId.value,
      page_no: pagination.page,
      page_size: pagination.pageSize,
      contact_info: searchForm.name || undefined,
      status: searchForm.status || undefined
    }
    
    const response = await getContactList(params)
    
    if (response.code === 1) {
      tableData.value = response.list || []
      pagination.total = response.count || 0
    } else {
      throw new Error(response.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取联系人列表失败:', error)
    ElMessage.error('获取数据失败，请重试')
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getList()
}

// 重置
const handleReset = () => {
  searchForm.name = ''
  searchForm.status = ''
  pagination.page = 1
  getList()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  pagination.page = 1
  getList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  getList()
}

// 返回
const handleBack = () => {
  router.back()
}

// 新增联系人
const handleAdd = () => {
  importType.value = 'manual'
  resetAddForm()
  addDialogVisible.value = true
}

// 编辑联系人
const handleEdit = (row: Contact) => {
  currentEditId.value = row.id
  editForm.contactInfo = row.contact_info || ''
  editDialogVisible.value = true
}

// 删除联系人
const handleDelete = async (row: Contact) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除联系人"${row.contact_info}"吗？`,
      '删除确认',
      {
        type: 'warning',
        confirmButtonText: '确定删除',
        cancelButtonText: '取消'
      }
    )
    
    const response = await deleteContact(row.id)
    
    if (response.code === 1) {
      ElMessage.success('删除成功')
      getList()
      fetchContactStats() // 刷新统计图表
    } else {
      throw new Error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除联系人失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 文件选择处理
const handleFileChange = (file: any) => {
  selectedFile.value = file.raw
  uploadProgress.value = 0
  uploadStatus.value = ''
  uploadProgressText.value = ''
}

// 文件移除处理
const handleFileRemove = () => {
  selectedFile.value = null
  uploadProgress.value = 0
  uploadStatus.value = ''
  uploadProgressText.value = ''
}

// 导入标签相关方法
const addImportTag = () => {
  const trimmedValue = importTagInputValue.value.trim()
  if (trimmedValue !== '' && !importTags.value.includes(trimmedValue)) {
    importTags.value.push(trimmedValue)
  }
  importTagInputValue.value = ''
  importTagInputVisible.value = false
}

const removeImportTag = (index: number) => {
  importTags.value.splice(index, 1)
}

const showImportTagInput = () => {
  importTagInputVisible.value = true
  nextTick(() => {
    importTagInputRef.value?.focus()
  })
}

// 下载模板
const downloadTemplate = () => {
  if(type.value == 1){
    window.open("https://washoustatic.oss-cn-shanghai.aliyuncs.com/06c23f2a-101a-44b5-b706-4891ec6b9242.xlsx","_blank");
  }

  if(type.value == 2){
      window.open("https://washoustatic.oss-cn-shanghai.aliyuncs.com/4e0a2bc7-d94e-490e-a615-88217ab33d9c.xlsx","_blank");
  }
}

// 提交新增
const handleAddSubmit = async () => {
  if (importType.value === 'manual') {
    await handleManualAdd()
  } else {
    await handleExcelAdd()
  }
}

// 手动添加
const handleManualAdd = async () => {
  if (!addFormRef.value) return
  
  try {
    const valid = await addFormRef.value.validate()
    if (!valid) return
    
    addSubmitLoading.value = true
    
    const data = {
      library_id: groupId.value,
      contact_info_arr: addForm.contacts.split('\n'),
      tag: manualTags.value
    }
    
    const response = await addContact(data)
    
    if (response.code === 1) {
      ElMessage.success('添加成功')
      addDialogVisible.value = false
      getList()
      fetchContactStats()
    } else {
      throw new Error(response.message || '添加失败')
    }
  } catch (error) {
    console.error('添加联系人失败:', error)
    ElMessage.error('添加失败，请重试')
  } finally {
    addSubmitLoading.value = false
  }
}

// Excel导入
const handleExcelAdd = async () => {
  if (!selectedFile.value) {
    ElMessage.warning('请选择要上传的Excel文件')
    return
  }
  
  try {
    addSubmitLoading.value = true
    uploadProgress.value = 10
    uploadStatus.value = ''
    uploadProgressText.value = '正在准备上传...'
    
    const formData = new FormData()
    formData.append('file', selectedFile.value)
    formData.append('library_id', String(groupId.value))
    
    // 添加标签信息
    if (importTags.value.length > 0) {
      // 将标签数组逐个添加到FormData中
      importTags.value.forEach((tag, index) => {
        formData.append(`tag[${index}]`, tag)
      })
    }
    
    uploadProgress.value = 30
    uploadProgressText.value = '正在上传文件...'
    
    const response = await importContactsFromExcel(formData)
    
    uploadProgress.value = 80
    uploadProgressText.value = '正在处理数据...'
    
    if (response.code === 1) {
      uploadProgress.value = 100
      uploadStatus.value = 'success'
      uploadProgressText.value = '导入完成！'
      
      ElMessage.success('导入成功' + response.count + '条数据')
      addDialogVisible.value = false
      getList()
      fetchContactStats() // 刷新统计数据
    } else {
      throw new Error(response.message || '导入失败')
    }
  } catch (error) {
    console.error('Excel导入失败:', error)
    uploadProgress.value = 100
    uploadStatus.value = 'exception'
    uploadProgressText.value = '导入失败，请重试'
    ElMessage.error('导入失败，请重试')
  } finally {
    addSubmitLoading.value = false
    
    // 3秒后重置进度条
    setTimeout(() => {
      uploadProgress.value = 0
      uploadStatus.value = ''
      uploadProgressText.value = ''
    }, 3000)
  }
}

// 提交编辑
const handleEditSubmit = async () => {
  if (!editFormRef.value || !currentEditId.value) return
  
  try {
    const valid = await editFormRef.value.validate()
    if (!valid) return
    
    editSubmitLoading.value = true
    
    const data = {
      contact_info: editForm.contactInfo.trim()
    }
    
    const response = await updateContact(currentEditId.value, data)
    
    if (response.code === 1) {
      ElMessage.success('编辑成功')
      editDialogVisible.value = false
      getList()
    } else {
      throw new Error(response.message || '编辑失败')
    }
  } catch (error) {
    console.error('编辑联系人失败:', error)
    ElMessage.error('编辑失败，请重试')
  } finally {
    editSubmitLoading.value = false
  }
}

// 重置新增表单
const resetAddForm = () => {
  addForm.contacts = ''
  selectedFile.value = null
  importTags.value = []
  importTagInputVisible.value = false
  importTagInputValue.value = ''
  uploadProgress.value = 0
  uploadStatus.value = ''
  uploadProgressText.value = ''
  addFormRef.value?.clearValidate()
  uploadRef.value?.clearFiles()
  manualTags.value = []
  manualTagInputVisible.value = false
  manualTagInputValue.value = ''
}

// 重置编辑表单
const resetEditForm = () => {
  editForm.contactInfo = ''
  currentEditId.value = null
  editFormRef.value?.clearValidate()
}

// 弹框关闭处理
const handleAddDialogClose = () => {
  resetAddForm()
}

const handleEditDialogClose = () => {
  resetEditForm()
}

// 页面初始化
onMounted(() => {
  if (!groupId.value) {
    ElMessage.error('缺少客群库信息')
    router.back()
    return
  }
  getList()
  fetchContactStats()
})

// 获取联系人状态统计
const fetchContactStats = async () => {
  try {
    statsLoading.value = true
    const response = await getContactStats(groupId.value)
    
    if (response.code === 1) {
      const data = response.data || {}
      
      // 状态配置
      const statusConfig = [
        { status: '0', name: '待投放', color: '#909399' },
        { status: '1', name: '投放中', color: '#E6A23C' },
        { status: '2', name: '已投放', color: '#67C23A' },
        { status: '3', name: '投放失败', color: '#F56C6C' }
      ]
      
      // 处理统计数据
    //   statsData.value = statusConfig.map(config => ({
    //     ...config,
    //     value: data[config.status] || 0
    //   }))

    statsData.value = data;

    //   console.log(data);
      
      totalContacts.value = response.count
      
      // 初始化图表
      initChart()
    } else {
      throw new Error(response.message || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取联系人统计失败:', error)
    ElMessage.error('获取统计数据失败，请重试')
  } finally {
    statsLoading.value = false
  }
}

// 初始化饼状图
const initChart = () => {
  if (!chartRef.value) return
  
  const chart = echarts.init(chartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      bottom: '0%',
      left: 'center',
      data: statsData.value.map(item => item.name)
    },
    series: [
      {
        name: '联系人状态',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '45%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: statsData.value.map(item => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: item.color
          }
        }))
      }
    ]
  }
  
  chart.setOption(option)
  
  // 监听窗口大小变化
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 手动标签相关方法
const addManualTag = () => {
  const trimmedValue = manualTagInputValue.value.trim()
  if (trimmedValue !== '' && !manualTags.value.includes(trimmedValue)) {
    manualTags.value.push(trimmedValue)
  }
  manualTagInputValue.value = ''
  manualTagInputVisible.value = false
}

const removeManualTag = (index: number) => {
  manualTags.value.splice(index, 1)
}

const showManualTagInput = () => {
  manualTagInputVisible.value = true
  nextTick(() => {
    manualTagInputRef.value?.focus()
  })
}
</script>

<style scoped>
.contacts-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-container {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.search-form {
  margin: 0;
}

/* 统计图表样式 */
.stats-section {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stats-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.stats-content {
  display: flex;
  gap: 20px;
  align-items: center;
  min-height: 280px;
}

.chart-container {
  flex: 1;
  height: 280px;
  min-width: 300px;
}

.stats-summary {
  flex: 0 0 200px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 15px;
}

.summary-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.summary-value {
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}

.summary-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.summary-stat {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 0;
}

.stat-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  flex-shrink: 0;
}

.stat-label {
  font-size: 13px;
  color: #606266;
  flex: 1;
}

.stat-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.table-section {
  margin-bottom: 20px;
}

.pagination-section {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.fail-reason {
  color: #f56c6c;
  font-size: 12px;
}

.import-type-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.manual-section {
  margin-top: 20px;
}

.excel-section {
  margin-top: 20px;
}

.excel-template {
  margin-top: 10px;
  text-align: center;
}

.security-notice {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.security-icon {
  font-size: 18px;
  color: #606266;
}

.security-text {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.template-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.template-header {
  margin-bottom: 10px;
}

.template-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.template-tips {
  margin-top: 10px;
  text-align: center;
}

.tags-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.tags-header {
  margin-bottom: 10px;
}

.tags-content {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.tags-tip {
  margin-top: 10px;
  text-align: center;
}

.upload-section {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.upload-header {
  margin-bottom: 10px;
}

.upload-area {
  width: 100%;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-tips {
  margin-top: 10px;
  text-align: center;
}

.progress-section {
  margin-top: 20px;
  text-align: center;
}

.progress-text {
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .contacts-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .header-left {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  /* 移动端统计图表优化 */
  .stats-content {
    flex-direction: column;
    min-height: auto;
    gap: 15px;
  }
  
  .chart-container {
    height: 200px;
    min-width: auto;
    width: 100%;
  }
  
  .stats-summary {
    flex: none;
    width: 100%;
    padding: 15px;
  }
  
  .summary-grid {
    flex-direction: row;
    flex-wrap: wrap;
    gap: 10px;
  }
  
  .summary-stat {
    flex: 1;
    min-width: calc(50% - 5px);
    justify-content: center;
    text-align: center;
    padding: 8px;
    background: #fff;
    border-radius: 6px;
    border: 1px solid #e4e7ed;
  }
  
  :deep(.el-table) {
    font-size: 12px;
  }
  
  .pagination-section {
    justify-content: center;
  }
}
</style> 